using System.Collections.Generic;
using Game.Core;
using Game.Main.Model;
using Game.Main.View;

namespace Game.Component
{
	public class BMachineItem : LinkRopeItem
	{
		private List<ItemComponentTrigger> triggers = new List<ItemComponentTrigger>();

		private ItemComponentTrigger target;

		private BaseItem displayer;

		public override void Init(ItemArchiveData data)
		{
			base.Init(data);
		}

		protected override void OnItemCompTriggerEnter(ColliderData collData)
		{
			base.OnItemCompTriggerEnter(collData);
			if (collData.trigger != null && collData.trigger.type == ItemComponentTrigger.Type.Body && collData.trigger.owner.itemData.scriptType == 1 && !triggers.Contains(collData.trigger))
			{
				triggers.Add(collData.trigger);
				target = collData.trigger;
				CheckDisplayerState();
			}
		}

		protected override void OnItemCompTriggerExit(ColliderData collData)
		{
			base.OnItemCompTriggerExit(collData);
			triggers.Remove(collData.trigger);
			if (collData.trigger == target)
			{
				if (triggers.Count > 0)
				{
					target = triggers[triggers.Count - 1];
				}
				else
				{
					target = null;
				}
				CheckDisplayerState();
			}
		}

		public override void TouchDown(TouchEventData touchEventData)
		{
			base.TouchDown(touchEventData);
			triggers.Clear();
			target = null;
		}

		public override void TouchUp(TouchEventData touchEventData)
		{
			base.TouchUp(touchEventData);
			triggers.Clear();
			target = null;
			CheckDisplayerState();
		}

		private void CheckDisplayerState()
		{
			if (target != null)
			{
				if (GetDisplayer() != null && target != null && target.owner != null)
				{
					((BMachineDisplayerItem)GetDisplayer()).ShowDisplayer((CharacterItem)target.owner);
				}
			}
			else if (GetDisplayer() != null)
			{
				((BMachineDisplayerItem)GetDisplayer()).ShowDisplayer(null);
			}
		}

		private BaseItem GetDisplayer()
		{
			if (displayer == null)
			{
				displayer = Singleton<Scene>.Instance.GetItemByScriptType(143);
			}
			return displayer;
		}
	}
}
